<template>
  <el-dialog v-model="showMorePanel" draggable :width="1200" :z-index="99">
    <div class="mb10">
      <tiny-button-group @change="doSearch" :data="groupData" v-model="checkedVal"></tiny-button-group>
    </div>
    <el-space>
      <el-input v-model="keyWord" size="default" placeholder="名称" @keydown.enter="doSearch" clearable style="width: 250px" />
      <lbtn @click="doSearch" :loading="loading">查询</lbtn>
    </el-space>
    <div class="mt20" style="display: flex">
      <div>
        <TGrid
            ref="tbRef"
            :fields="columns"
            :grid-height="600"
            :data-list="tableData"
            click-row-to-select
            :show-footer="false"
            show-page
            @change-page="pageChange"
        />
      </div>
      <div style="width: 280px; padding-left: 15px">
        <el-scrollbar :height="600">
          <tiny-tree
              :data="treeList"
              :expand-on-click-node="false"
              :show-line="true"
              :default-expand-all="true"
              @node-click="handleNodeClick"
          ></tiny-tree>
        </el-scrollbar>
      </div>
    </div>
    <div class="mt20 tc" style="display: flex">
      <div style="flex: 1; text-align: left">
      </div>
      <div>
        <lbtn type="primary" size="medium" @click="confirm" style="width: 150px">选中</lbtn>
        <lbtn size="medium" @click="confirmClose" style="width: 150px">选中并关闭</lbtn>
        <lbtn size="medium" @click="showMorePanel = false" style="width: 150px">关闭</lbtn>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import tool from "@/utils/tool";
import { Tree,ButtonGroup,Pager } from '@opentiny/vue'
export default {
  name: 'popGood',
  props:{
    width: {type: [String, Number], default: ''},
    modelValue: {type: [String, Number], default: ''},
    invId: {type: [String, Number], default: ''},
    unit: {type: [String, Number], default: ''},
    transType: {type: [String, Number], default: 150601},
    qty: {type: [String, Number], default: ''},
    sql: {type: String, default: ''},
    size: {type: String, default: 'default'},
    valueKey: {type: String, default: 'id'},
    labelKey: {type: String, default: 'name'},
    moreCat: {type: String, default: 'goods'},
    searchKey: {type: String, default: ''},
    height: {type: [String, Number], default: ''},
    showMore: {type: Boolean, default: false},
    loadOnce: {type: Boolean, default: false},
    addItem: {type: Boolean, default: false},
    disabled: {type: Boolean, default: false},
    autoSelect: {type: Boolean, default: false},
    clearable: {type: Boolean, default: true},
    isGrid: {type: Boolean, default: false}, // 下拉 表格
    list: {type: [String, Array], default: ''},
    focusOpen: {type: Boolean, default: true}, // focus自动打开
    readonly: {type: Boolean, default: false}, // 必填
    required: {type: Boolean, default: false}, // 必填
    pinYin: {type: Boolean, default: false}, // 拼音
    border: {type: Boolean, default: true}, // 禁用
    className: {type: String, default: ''}, // 自定义样式
    borderColor: {type: String, default: ''}, // 边框色
    bgColor: {type: String, default: ''}, // 背景色
    listWidth: {type: Number, default: 0}, // 下拉框宽度
    cat: {type: String, default: ''}, // 取数据cat分类
    placeholder: {type: String, default: ''}, // 取数据cat分类
    options: {type: Array, default: () => { return [] }}, // 如果传入值
  },
  components: {
    TinyTree: Tree,
    TinyButtonGroup: ButtonGroup,
    TinyPager: Pager
  },
  data () {
    return {
      show: false,
      loading: false,
      showMorePanel: false,
      buId: 1,
      currentPage: 1,
      pageSize: 30,
      total: 0,
      groupData: [
        { text: '商品', value: '商品' },
        { text: '近期交易', value: '近期交易' },
      ],
      checkedVal:'商品',
      state: {
        list: this.list
      },
      currentIndex: -1,
      keyWord: '',
      goodsCat: '',
      goodsCatId: '',
      tableData: [],
      columns: [
        {type: 'index', width: 50},
        {type: 'selection', width: 50,align: 'center'},
        {field: 'name', title: '名称', width: 300,align: 'left',filter: true,sortable: true},
        {field: 'unit', title: '单位', width: 80,align: 'center'},
        {field: 'spec', title: '规格', width: 80,align: 'center'},
        {field: 'price', title: '价格', width: 80,align: 'right',formatter: 'formatMoney'},
        {field: 'leftQty', title: '库存', width: 80,align: 'center',formatter: 'formatQty',sortable: true},
        {field: 'qty', title: '本次数量', width: 100,align: 'right',editor:{ component: 'input', autoselect: true  }  },

      ],
      treeList: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
    }
  },
  emits: ['update:modelValue', 'update:id', 'change', 'enter', 'Esc', 'down', 'up', 'left', 'right', 'itemAdd','moreSelect'],
  watch: {
    list: {
      handler (val) {
        this.state.list = val
      },
      deep: true
    },
    modelValue (val) {
      if(!val) this.$emit('update:id', null)
    }
  },
  methods: {
    pageChange (data) {
      this.pageSize = data.pageSize
      this.currentPage = data.currentPage
      this.getPopList()
    },
    handleNodeClick (data) {
      this.goodsCatId = data.id
      this.getPopList()
    },
    changeCat (ret) {
      this.goodsCatId = ret ? ret.id : null
    },
    confirm () {
      let sel = this.$refs.tbRef.getSelected()
      if(sel.length === 0) return tool.err('至少选择一行')
      sel.map(row => {
        row.qty = tool.xe.toNumber(row.qty)
      })
      this.$emit('moreSelect', sel)
      this.$refs.tbRef.removeSelecteds()
    },
    confirmClose () {
      let sel = this.$refs.tbRef.getSelected()
      if(sel.length === 0) return tool.err('至少选择一行')
      sel.map(row => {
        row.qty = tool.xe.toNumber(row.qty)
      })
      this.$emit('moreSelect', sel)
      this.showMorePanel = false
    },
    cellClick({row, column}) {
      if(column.property !== 'qty')
        this.$refs.tbRef.toggleCheckboxRow(row)
    },
    cellClick1({row, column}) {
      if(column.property !== 'qty')
        this.$refs.tbGoodRef.toggleCheckboxRow(row)
    },
    doSearch () {
      this.getPopList()
    },
    openChose (initTxt = '', buId = 0) {
      this.buId = buId
      tool.post('dropdown/goodCatList').then(ret => {
        let list = [
          {id: 0,label:'全部', children: tool.toArrayTree(ret.data)}
        ]
        this.treeList = list
      })
      this.getPopList()
      this.showMorePanel = true
    },
    getPopList () {
      this.loading = true
      setTimeout(() => {
        this.loading = false
      }, 5000)
      tool.post('dropdown/invList',{
        buId: this.buId,
        transType: this.transType,
        keyWord: this.keyWord,
        goodsCatId: this.goodsCatId,
        checkedVal: this.checkedVal,
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        cat: 'invList'
      }).then(ret => {
        this.tableData = ret.data.list
        this.$refs.tbRef.setData(ret.data.total, ret.data.list)
        this.total = ret.data.total
        this.loading = false
      })
    },
    focusEvent () {
      if(this.focusOpen) {
        this.currentIndex = -1
        if(!this.modelValue)
          this.changeInput(this.modelValue)
      }
    },
    blurEvent () {

    },
    isOpen () {
      return this.$refs.pullRef.isPanelVisible()
    },
    keydownEvent (e) {
      let key = e.key ? e.key : e.$event.key
      let start = e.target.selectionStart // 光标位置
      switch (key) {
        case 'Enter': {
          if(this.currentIndex > -1 && this.currentIndex < this.state.list.length) {
            this.setData(this.state.list[this.currentIndex])
            this.currentIndex = -1
          }
          if(this.currentIndex === -1) {
            if(this.state.list && this.state.list.length === 1) {
              this.setData(this.state.list[0])
              this.$emit('enter')
            }
            else {
              if(!this.modelValue || !this.invId) {
                this.openChose(this.modelValue)
              }
              else {
                this.$emit('enter')
              }
            }
          }
          if(!this.isOpen()) {
            // this.$emit('enter')
          }
        } break
        case 'ArrowLeft': {
          if(start === 0) {
            this.$emit('left')
          }
        }
          break
        case 'ArrowRight': {
          if(start === (this.modelValue?tool.xe.toString(this.modelValue).length:0)) {
            this.$emit('right')
          }
        }
          break
        case 'ArrowDown': {
          if(!e.ctrlKey) {
            if(this.isOpen()) {
              if(this.currentIndex < this.state.list.length - 1) {
                this.currentIndex++
                this.scrollToOption(true, this.state.list[this.currentIndex])
              } else {
                let optWrapperElem = this.$refs.wrapperRef;
                this.currentIndex = 0
                optWrapperElem.scrollTo(0, 0)
              }
            }
            else {
              this.$emit('down')
            }
          }
        } break
        case 'ArrowUp': {
          if(!e.ctrlKey) {
            if(this.isOpen()) {
              if(this.currentIndex > 0 && this.currentIndex <= (this.state.list.length-1)) {
                this.currentIndex--
              } else {
                this.currentIndex = this.state.list.length - 1
              }
              this.scrollToOption(false, this.state.list[this.currentIndex])
            }
            else {
              this.$emit('up')
            }
          }
        } break
        case 'Escape': {
          this.$emit('Esc')
        } break
      }
    },
    clear () {
      this.$emit('update:modelValue', null)
      this.$emit('update:id', null)
      this.$emit('change', null)
      this.currentIndex = -1
    },
    changeInput (value) {
      if(this.disabled) return
      this.$emit('update:modelValue', value)
      if(this.loadOnce) {
        if(this.state.list.length > 0) {
          return;
        }
      }
      let searchTxt = value?tool.xe.trim(value):'';
      if(this.list.length > 0) {
        if(searchTxt) {
          this.state.list = this.list.filter(row => {
            return row[this.labelKey].indexOf(searchTxt) !== -1
          })
        }
        this.openPanel()
      }
      else if (this.sql) {
        let sql = this.sql
        if(searchTxt) {
          if(this.pinYin) {
            sql += ` and (${this.labelKey} like '%${searchTxt}%' or pinYin like '%${searchTxt}%') `
          }
          else {
            sql += ` and ${this.labelKey} like '%${searchTxt}%' `
          }
        }
        tool.post('common/doSql', {sql: sql}).then(ret => {
          if(ret.data && ret.data.length > 0) {
            this.state.list = ret.data
            this.openPanel()
          }
        })
      }
      else if (this.cat) {
        this.state.list = []
        tool.post('common/dropdown', {cat: this.cat, keyWord: searchTxt, invId: this.invId,buId: this.buId,unit: this.unit, transType: this.transType,qty: this.qty}).then(ret => {
          if(ret.stat) {
            if(ret.data && ret.data.length > 0) {
              this.state.list = ret.data
              this.openPanel()
            }
          }
        })
      }
    },
    openPanel () {

    },

    mouseDown (e, item) {
      e.preventDefault()
      this.setData(item)
      this.currentIndex = -1
      setTimeout(() => {
        this.$emit('enter')
      }, 0)
    },
    scrollToOption (isAlignBottom, item) {
      let optWrapperElem = this.$refs.wrapperRef;
      let panelElem = this.$refs.wrapperRef;
      let optElem = panelElem.querySelector("#id"+item.id);
      if (optWrapperElem && optElem) {
        let wrapperHeight = panelElem.offsetHeight;
        let offsetPadding = 5;
        if (isAlignBottom) {
          if (optElem.offsetTop + optElem.offsetHeight - panelElem.scrollTop > wrapperHeight) {
            optWrapperElem.scrollTo(0, optElem.offsetTop + optElem.offsetHeight - wrapperHeight)
          }
        }
        else {
          optWrapperElem.scrollTo(0, optElem.offsetTop - offsetPadding)
        }
      }
    },
    setData (item) {
      let id = item[this.valueKey]
      let text = item[this.labelKey]
      this.$emit('update:modelValue', text)
      this.$emit('update:id', id)
      this.$emit('change', item)
    },
    down (e) {
      e.preventDefault()
    },
    addItemClick () {
      this.$emit('itemAdd')
    },
  }
}
</script>

<style lang="scss">
.list-item2 {
  height: 30px;
  line-height: 30px;
  padding-left: 5px;
  padding-right: 5px;
  white-space: nowrap;
  display: flex;
  &.active {
    background-color: #dcdfe6;
  }
  &:hover {
    background-color: #dcdfe6;
    cursor: pointer;
  }
}
.el-input-group__append {
  padding: 0 2px !important;
}
.more {
  &:hover {
    cursor: pointer;
  }
}
.pull-wrapper {
  height: 1200px;
  min-width: 150px;
  //overflow: auto;
  //position: absolute;
  background-color: white;
  //box-shadow: 0 2px 5px 0 #E5E5E5;
  //box-shadow: 0 0 6px 2px rgba(0, 0, 0, 0.1);
  width: auto;
}
.add-row {
  height: 40px;
  line-height: 40px;
  text-align: center;
  color: #8a8f97;
  background-color: var(--el-bg-color-page);
  border-left: var(--el-border);
  border-right: var(--el-border);
  border-bottom: var(--el-border);
  &:hover {
    cursor: pointer;
    color: #1e9fff;
  }
}
</style>